package org.linlinjava.litemall.core.redis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.db.domain.LitemallSchool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoLocation;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

/**
 * spring redis 工具类
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;
    
    
    
	 /**
     * 存入redis GEO缓存
     * @param key 键  
     * @param longitude   经度   String类型
     * @param latitude   纬度   String类型
     * @param member  店铺id
     * @return true/false
    */
    public boolean setGeo(String key,double longitude, double latitude,String member){
        boolean result = false;
        try {
        redisTemplate.opsForGeo().add(key,new Point(longitude,latitude),member);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 批量添加位置信息
     * @param key
     * @param memberCoordinateMap
     * @return
     */
    public boolean setboundGeoOps(String key,Map<String, Point> memberCoordinateMap){
        boolean result = false;
        try {
        	redisTemplate.boundGeoOps(key).add(memberCoordinateMap);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
	 /**
     * 移除地理位置信息
     * @param key
     * @param members  店铺id
     * @ReturnType：boolean
     */
    public boolean removeGeo(String key, String members) {
        try {
             redisTemplate.opsForGeo().remove(key,members);
        } catch (Throwable t) {
            //logger.error("移除[" + key +"]" + "失败" +", error[" + t + "]");
        }
        return true;
    }
    
    
    /**
     * 获得某个位置的经纬度
     * @param key 键
     * @param member  店铺id
     *
    */
    public List<Point> getGeo(String key,String member){
        try {
            GeoOperations<String, String> geoOps = redisTemplate.opsForGeo();
            List<Point> position = geoOps.position(key, member);
            return position;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    /**
     * 根据给定地理位置坐标获取指定范围内的地理位置集合
     * @param key  键
     * @param longitude  经度   String类型
     * @param latitude   纬度   String类型
     * @param distance  距离  没有时默认5km
     * @return list  商家id集合
    */
    public List<LitemallSchool> getShopIdByGeo(String key, double longitude, double latitude, String mi){
        double distance = Double.valueOf(StringUtils.isEmpty(mi)?"3000":mi);//不选择时，默认3000m
        List<LitemallSchool> geos = new ArrayList<>();
        BoundGeoOperations boundGeoOperations = redisTemplate.boundGeoOps(key);
        Point point = new Point(longitude, latitude);
        Circle within = new Circle(point, distance);
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiusArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
        //返回的结果包括 距离 和 坐标
          geoRadiusArgs = geoRadiusArgs.includeDistance();
        //限制查询返回的数量
        // geoRadiusArgs.limit(10);
        //按查询出的坐标距离中心坐标的距离进行排序
        geoRadiusArgs.sortAscending();
        GeoResults<GeoLocation<String>> geoResults = boundGeoOperations.radius(within, geoRadiusArgs);
        List<GeoResult<GeoLocation<String>>> geoResultList = geoResults.getContent();
        
        LitemallSchool geoVo = null;
        for (GeoResult<GeoLocation<String>> geoResult : geoResultList) {
            geoVo = new LitemallSchool();
            String name = geoResult.getContent().getName();
            Distance distance1 = geoResult.getDistance();
            geoVo.setSchoolName(name);
            String str = String.valueOf(distance1);
            String m1 = StringUtils.substringBeforeLast(str, "M");
            geoVo.setDistance(m1);
            geos.add(geoVo);
        }
        return geos;
    }
    
    
    
    /**
     * 判断缓存中是否有值
     * @param key
     * @return
     */
    public boolean hasData(String key) {
    	boolean result = redisTemplate.hasKey(key);
    	return result;
    }
    
    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> long setCacheSet(final String key, final Set<T> dataSet)
    {
        Long count = redisTemplate.opsForSet().add(key, dataSet);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }
    
    
    
    /**
     * 递增 适用场景： https://blog.csdn.net/y_y_y_k_k_k_k/article/details/79218254 高并发生成订单号，秒杀类的业务逻辑等。。
     * 
     * @param key
     *            键
     * @param by
     *            要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
    
    
    /**
     * 普通缓存获取
     * 
     * @param key
     *            键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    
    
    public void setPage(String key, String value, double score) {
    	redisTemplate.opsForZSet().add(key, value, score);
    }
    
    public Set<String> getPage(String key, int offset, int count) {
    	return redisTemplate.opsForZSet().rangeByScore(key, 1, 100000, (offset-1)*count, count);
    }
    
    
    public void deleteObject() {
        //清除缓存
        deleteObject("schoolType_new_1");
        deleteObject("schoolType_new_2");
        deleteObject("schoolType_new_3");
    }
}
